package org.example.controller;

import org.example.Entity.Commodity;
import org.example.Entity.CommodityVO;
import org.example.Entity.Result;
import org.example.service.CommodityService;
import org.example.utils.GsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 商品API
 */
@Validated
@RestController
@RequestMapping("/api/commodity")
public class CommodityController {

    @Autowired
    private CommodityService commodityService;

    @PostMapping("/list")
    public Result<CommodityVO> list(@RequestBody String paramStr){
        Map<String, Object> paramMap = GsonUtil.jsonToMap(paramStr);
        //1.分页查询商品列表
        List<Commodity> list = commodityService.list((String) paramMap.get("keyword"), (Integer) paramMap.get("page_number"), (Integer) paramMap.get("page_size"));
        int total = commodityService.getTotal((String) paramMap.get("keyword"));
        //2.返回结果
        return Result.success(new CommodityVO(total,list));
    }

    @GetMapping("/{id}")
    public Result<Commodity> info(@PathVariable("id")Integer id){
        Commodity commodity = commodityService.findCommodityById(id);
        return Result.success(commodity);
    }

}
